package com.finance.aop;

import com.finance.framework.lang.Page;
import com.finance.framework.qurtz.RedisRunningStatusAcquirer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.quartz.JobExecutionContext;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;

/**
 * Created by CBWL on 2017/4/28.
 */
@Aspect
public class JobAop {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisRunningStatusAcquirer redisRunningStatusAcquirer;

    public void setRedisRunningStatusAcquirer(RedisRunningStatusAcquirer redisRunningStatusAcquirer){
        this.redisRunningStatusAcquirer = redisRunningStatusAcquirer;
    }
    //@Around("execution(public void execute(..)) and this(com.finance.scheduler.service.AbstractTask) && !this(com.finance.scheduler.job.DataExtractJob) && !this(com.finance.scheduler.job.RecomputeJob)")
      public Object aroundProceed(ProceedingJoinPoint jp) throws Throwable {
        this.logger.info("before:" + Arrays.toString(jp.getArgs()));
        Object[] args = jp.getArgs();
        JobExecutionContext jobExecutionContext = (JobExecutionContext)args[0];
        TriggerKey triggerKey = jobExecutionContext.getTrigger().getKey();
        Page page = this.redisRunningStatusAcquirer.acquirePage(triggerKey);
        jobExecutionContext.getJobDetail().getJobDataMap().put("page",page);
        Object object = jp.proceed(args);
        this.redisRunningStatusAcquirer.putback(triggerKey,page);
        this.logger.info("after:" + Arrays.toString(jp.getArgs()));
        return object;
      }
    //@Around("execution(public void execute(..)) &&  ( this(com.finance.scheduler.job.DataExtractJob) || this(com.finance.scheduler.job.RecomputeJob) )")
      public Object aroundCompute(ProceedingJoinPoint jp) throws Throwable {
        this.logger.info("before:" + Arrays.toString(jp.getArgs()));
        Object[] args = jp.getArgs();
        JobExecutionContext jobExecutionContext = (JobExecutionContext)args[0];
        TriggerKey triggerKey = jobExecutionContext.getTrigger().getKey();
        //PageBlockingQueue queue= this.runningStatusAcquirer.acquireQueue(triggerKey);
        //jobExecutionContext.getJobDetail().getJobDataMap().put("queue",queue);
        Object object = jp.proceed(args);
        this.logger.info("after:" + Arrays.toString(jp.getArgs()));
        return object;
      }

}
